package ar.republicagroup.gestion.dao.jpa;

import ar.republicagroup.gestion.dao.ClienteSaldoDAO;
import ar.republicagroup.gestion.entities.Cliente;
import ar.republicagroup.gestion.entities.ClienteSaldo;
import ar.republicagroup.gestion.util.JPAUtil;
import ar.republicagroup.gestion.util.messages.UIMessages;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.Query;
import org.apache.log4j.Logger;

/**
 *
 * @author DIEGOALV
 */
public class ClienteSaldoDAOImplJPA implements ClienteSaldoDAO{
    
        private static Logger            log = Logger.getLogger(ClienteDAOImplJPA.class);
	private EntityManager		 em;
        
        
        
    public ClienteSaldoDAOImplJPA() {
        em = JPAUtil.getEntityManager();
    }
    

        
        
    @Override
    public List<ClienteSaldo> findEntities() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public ClienteSaldo getSaldoActualByCliente(Cliente cliente) {
        try{
            Query query   = em.createQuery("SELECT cs FROM ClienteSaldo cs WHERE cs.id = (SELECT MAX(cs2.id) FROM ClienteSaldo cs2 WHERE cs2.clienteId = ?1)");
            query.setParameter(1, cliente);
            return (ClienteSaldo)query.getSingleResult();
        }catch(NoResultException ex){
            log.error(ex.getMessage());
            return null;
        }
    }

    @Override
    public String insert(ClienteSaldo nuevoSaldo) {
            if(!em.isOpen()) { em = JPAUtil.getEntityManager(); }
            
                log.info(nuevoSaldo.getSaldoActual());
               
                String mensaje = null;
                try {
                    em.clear();
                    em.getTransaction().begin();
                    em.persist(nuevoSaldo);
                    em.getTransaction().commit();
                    mensaje = UIMessages.getInfoMessage("onCompleteInsert"); 
                }catch(Exception ex){
                    log.error("Error al registrar un nuevo saldo",ex);
                    em.getTransaction().rollback();
                }
            
                return mensaje;
    }
    
}
